<?php
namespace User\Controller;
use Think\Controller;
use Think\Page;
use User\Controller\UserController;
use Common\Service\Sms\ShortMessageService;
use User\Model\RedPacketModel;

class RedPacketController extends UserController
{
    public function index()
    {
        $red_packet = M('redpacket');
        $where['token'] = $this->wxuser['token'];
        $where['status'] = array('NEQ', RedPacketModel::STATUS_DELETE);
        $where['keyword'] = array('not in', array('niudan', 'lottery'));

        $count = $red_packet->where($where)->count();

        $page = new Page($count, 10);
        $show = $page->show();

        $list = $red_packet->where($where)->limit($page->firstRow.','.$page->listRows)->order('id desc')->select();

        if(!empty($list)){
            foreach ($list as &$value){
                $value['link'] = "http://" . $_SERVER['SERVER_NAME'] . "/Wap/RedPacket/index?id=".$value['id'];
            }
        }
        $this->assign("page", $show);
        $this->assign("list", $list);
        $this->display();
    }

    public function edit()
    {
        $id = I( "get.id", -1, "" );
        $condition['id'] = $id;
        $condition['token'] = $this->wxuser['token'];
        $red_packet = M( "redpacket" )->where( $condition )->find();
        $red_packet_items = array();
        $first_red_packet = '';
        //奖项
        if($id != -1){
            $item_condition['redpacket_id'] = $id;
            $item_condition['status'] = RedPacketModel::STATUS_ACTIVE;
            $red_packet_items = M( "redpacket_item" )->where( $item_condition )->order('id asc')->select();
            if(!empty($red_packet_items)){
                foreach ($red_packet_items as $key => $value){
                    $red_packet_items[$key]['attribute'] = unserialize($value['attribute']);
                }
            }
            $first_red_packet = $red_packet_items[0]['id'];     //第一个奖项的id，编辑时需要
        }
        $levels = RedPacketModel::getLevel('all');
        $red_packet_upload = M( "redpacket_upload" )->where( ['redpacket_id' => $id] )->find();
        $red_packet_upload['bgm'] = $red_packet_upload['bgm']?$red_packet_upload['bgm']:'Public/Uploads/redpacket/bgm.mp3';
        $default_container = '<p style="text-align: left;"><span style="font-size: 18px;"><strong style="color: rgb(192, 0, 0); font-family: 微软雅黑, &quot;Microsoft YaHei&quot;; font-size: 20px;">活动时间：</strong></span></p><p style="text-align: left;"><span style="font-size: 18px; font-family: 微软雅黑, &quot;Microsoft YaHei&quot;; background-color: rgb(255, 255, 255); color: rgb(127, 127, 127);">2017-xx-xx ~ 2017-xx-xx</span></p><p style="text-align: left;"><strong style="color: rgb(192, 0, 0); font-family: 微软雅黑, &quot;Microsoft YaHei&quot;; font-size: 20px;"><br/></strong></p><p style="text-align: left;"><span style="font-size: 18px;"><strong style="color: rgb(192, 0, 0); font-family: 微软雅黑, &quot;Microsoft YaHei&quot;; font-size: 20px;">活动说明：</strong></span></p><p><span style="font-size: 18px; font-family: 微软雅黑, &quot;Microsoft YaHei&quot;; background-color: rgb(255, 255, 255); color: rgb(127, 127, 127);">1、游戏开始<img src="/Public/images/RedPacket/icon/ico_redpacket.png" title="ico_redpacket.png" alt="ico_redpacket.png"/>飞落下来，点击红包有一定几率<span style="background-color: rgb(73, 68, 41); font-size: 18px; font-family: 微软雅黑, &quot;Microsoft YaHei&quot;;"></span>会是奖品，也有可能什么都没<img src="/Public/images/RedPacket/icon/ico_none.png" title="ico_none.png" alt="ico_none.png"/>，但千万不要点到<img src="/Public/images/RedPacket/icon/ico_bomb.png" title="ico_bomb.png" alt="ico_bomb.png"/>，游戏会直接结束。</span></p><p><span style="font-size: 18px; font-family: 微软雅黑, &quot;Microsoft YaHei&quot;; background-color: rgb(255, 255, 255); color: rgb(127, 127, 127);">2、每个用户ID每天最多只可以玩xx次。</span></p><p><strong style="color: rgb(192, 0, 0); font-family: 微软雅黑, &quot;Microsoft YaHei&quot;; font-size: 20px;"><br/></strong></p><p><span style="font-size: 18px;"><strong style="color: rgb(192, 0, 0); font-family: 微软雅黑, &quot;Microsoft YaHei&quot;; font-size: 20px;">活动奖品：</strong></span></p><p><span style="font-size: 18px; font-family: 微软雅黑, &quot;Microsoft YaHei&quot;; background-color: rgb(255, 255, 255); color: rgb(127, 127, 127);">x等奖x名xxx<br/></span></p><p><span style="font-size: 18px; font-family: 微软雅黑, &quot;Microsoft YaHei&quot;; background-color: rgb(255, 255, 255); color: rgb(127, 127, 127);"><span style="color: rgb(127, 127, 127); font-family: 微软雅黑, &quot;Microsoft YaHei&quot;; font-size: 18px; background-color: rgb(255, 255, 255);">x等奖x名xxx</span></span></p>';
        $this->assign( "id", $id );
        $this->assign( "default_container", $default_container );
        $this->assign( "red_packet_items", $red_packet_items );
        $this->assign( "red_packet", $red_packet );
        $this->assign( "f", $first_red_packet );
        $this->assign( "levels", $levels );
        $this->assign( "red_packet_upload", $red_packet_upload );
        $this->display();
    }

    public function update()
    {
        $id = I( "post.id", -1, "" );
        $data = array(
            'title' => I( "post.title", "", "" ),
            'token' => $this->wxuser['token'],
            'startdate' => I( "post.startdate", "", "" ),
            'enddate' => I( "post.enddate", "", "" ),
            'info' => I( "post.info", "", "" ),
            'number_limits' => I( "post.number_limits", "-1", "" ),
            'per_num_sum' => I( "post.per_num_sum", "-1", "" ),
            'per_num' => I( "post.per_num", "", "" ),
//            'total_rate' => I( "post.total_rate", "", "" ),
            'createdate' => date('Y-m-d H:i:s'),
            'keyword' => I( "post.keyword", "", "" ),
            'desc' => I( "post.desc", "", "" ),
            'game_time' => I( "post.game_time", "30", "" ),
            'share_title' => I( "post.share_title", "", "" ),
            'share_desc' => I( "post.share_desc", "", "" ),
            'share_link' => I( "post.share_link", "", "" ),
            'share_play' => I( "post.share_play", 0, "" ),
            'share_able' => I( "post.share_able", 0, "" )
        );

        //---使用临时字段--
        $reserve['end_speed'] = I( "post.end_speed", "3", "" );
        $reserve['start_speed'] = I( "post.start_speed", "0.2", "" );
        $reserve['redpacket_rate'] = I( "post.redpacket_rate", "0.65", "" );
        $reserve['again_url'] = I( "post.again_url", "", "" );
        $data['reserve'] = json_encode($reserve);
        //--使用临时字段结束--

        $award_num = I( "post.award_num", "0", "" );
        $info = $this->upload();
        $award_data = $info['award_data'];
        $upload_data = $info['upload_data'];
        //图文推送封面
        $data['picurl'] = $award_data[0]['pic'];
        //分享图标
        $data['share_img'] = $award_data[11]['pic'];

        $red_packet = M( "redpacket" );
        $red_packet_item = M( "redpacket_item" );
        $red_packet_upload = M( "redpacket_upload" );
        $result = null;
        if( $id != -1 && !empty( $id) ){
            $data['id'] = $id;
            $result['updated'] = $red_packet->save( $data );
            $result['success'] = $result['updated'];
            if($upload_data != ''){
                $red_packet_upload->where(['redpacket_id'=>$id])->save(array('bgm'=>$upload_data));
            }
            if($award_num > 0){
                foreach ($award_data as $key => $value){
                    if($key > 0 && $key <= 10){
                        $new_award_data = array(
                            'name' => $value['name'],
                            'level' => $value['level'],
                            'number' => $value['number'],
                            'reserve' => $value['reserve'],
                            'pic' => $value['pic'],
                            'attribute' => $value['attribute']
                        );
                        if($value['item_id'] && $value['item_id'] > 0){
                            $red_packet_item->where(['id'=>$value['item_id']])->save($new_award_data);
                        }else{
                            $new_award_data['redpacket_id'] = $id;
                            $new_award_data['status'] = $value['status'];
                            $red_packet_item->add($new_award_data);
                        }
                    }
                }
            }
        }else{
            $data['id'] = $red_packet->add( $data );
            $result['id'] = $data['id'];
            $result['added'] = $data['id'] ? true : false;
            $result['success'] = $result['added'];
            $red_packet_upload->add(array('redpacket_id'=>$data['id'], 'bgm'=>$upload_data));
            if($award_num > 0){
                foreach ($award_data as $key => $value){
                    if($key > 0 && $key <= 10){
                        $new_award_data[] = array(
                            'redpacket_id' => $data['id'],
                            'name' => $value['name'],
                            'level' => $value['level'],
                            'number' => $value['number'],
                            'reserve' => $value['reserve'],
                            'pic' => $value['pic'],
                            'attribute' => $value['attribute'],
                            'status' => $value['status']
                        );
                    }
                }
                $red_packet_item->addAll($new_award_data);
            }
        }
        if( $data['keyword']!='' && $result['success'] ){
            $deleted = M( "keyword" )->where( array( "token" => $this->wxuser['token'], 'pid' => $data['id'], 'module' => 'RedPacket' ) )->delete();
            $keywords = explode(",", $data['keyword']);
            if( $deleted !== false ){
                foreach( $keywords as $keyword ){
                    $added = M( "keyword" )->add( array( "keyword" => $keyword, "pid" => $data['id'], "token" => $this->wxuser['token'], "module" => "RedPacket" ) );
                    if( !$added ){
                        $result['success'] = false;
                    }
                }
            }else if( $deleted === false ){
                $result['success'] = false;
            }
        }
        if( $result['success'] > 0 || ($result['success'] === 0 && $data['id'] > 0)){
            $this->success( "保存成功", "/User/RedPacket/index");
        }else{
            $this->error( "保存失败", "/User/RedPacket/index");
        }
    }

    public function deletes()
    {
        $ids = I( "get.ids", "", "" );
        if(!empty($ids)){
            $ids = explode('|', $ids);
        }
        $condition['id'] = array('IN', $ids);
        $condition['token'] = $this->wxuser['token'];
        $updated = M( "redpacket" )->where( $condition )->save( array('status'=>RedPacketModel::STATUS_DELETE ));
        if( $updated ){
            $this->success( "删除成功", "", true);
        }else{
            $this->error( "删除失败", "", true);
        }
    }

    //编辑时，删除奖项
    public function deleteItem()
    {
        $condition['id'] = I( "get.id", "", "" );
        $updated = M( "redpacket_item" )->where( $condition )->save( array('status'=>RedPacketModel::STATUS_DELETE));
        if( $updated ){
            $this->success( "删除奖项成功", "", true);
        }else{
            $this->error( "删除奖项失败", "", true);
        }
    }

    public function updateData()
    {
        $status = I("get.status", "", "");
        $condition['id'] = I( "get.id", "", "" );
        $condition['token'] = $this->wxuser['token'];
        if($status == RedPacketModel::STATUS_ACTIVE){
            $updated = M( "redpacket" )->where( $condition )->save( array('status'=>RedPacketModel::STATUS_ACTIVE));
        }elseif($status == RedPacketModel::STATUS_STOP){
            $updated = M( "redpacket" )->where( $condition )->save( array('status'=>RedPacketModel::STATUS_STOP));
        }else{
            $updated = M( "redpacket" )->where( $condition )->save( array('status'=>RedPacketModel::STATUS_DELETE));
        }
        if( $updated ){
            if($status == RedPacketModel::STATUS_ACTIVE){
                $this->success( "发布成功", "", true);
            }elseif($status == RedPacketModel::STATUS_STOP){
                $this->success( "停用成功", "", true);
            }else{
                $this->success( "删除成功", "", true);
            }
        }else{
            $this->error( "操作失败", "", true);
        }
    }

    private function upload()
    {
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728;// 设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg', 'mp3', 'mp4', 'wav');// 设置附件上传类型
        $upload->rootPath = './Public/Uploads/redpacket/'; // 设置附件上传根目录
        $upload->subName = array("date", "Ymd");
        $upload->saveName = array("uniqid", "redpacket");
        // 上传文件
        $info = $upload->upload();
        //设置音频文件
        if(!empty($info['bgm'])){
            $upload_data = 'Public/Uploads/redpacket/' . date('Ymd') . '/' . $info['bgm']['savename'];
        }else{
            $upload_data = '';
        }
        //图文推送封面
        if(I("post.picurl","","")){
            $picurl0 = I("post.picurl","","");
        }elseif($info['picurl']['savename']){
            $picurl0 = 'Public/Uploads/redpacket/' . date('Ymd') . '/' . $info['picurl']['savename'];
        }else{
            $picurl0 = '';
        }
        $award_data[0] = array(
            'pic' => $picurl0
        );
        //分享图标
        if(I("post.picurl11","","")){
            $picurl11 = I("post.picurl11","","");
        }elseif($info['picurl11']['savename']){
            $picurl11 = 'Public/Uploads/redpacket/' . date('Ymd') . '/' . $info['picurl11']['savename'];
        }else{
            $picurl11 = '';
        }
        $award_data[11] = array(
            'pic' => $picurl11
        );
        //奖品图片
        $img = "";
        for($i=1;$i<=10;$i++){
            if(!empty($_POST['name'.$i])){
                $picurl = $info['picurl'.$i];
                $pic = $_POST['pic'.$i];
                if(!empty($pic)){
                    $img = $pic;
                }elseif(!empty($picurl)){
                    $img = 'Public/Uploads/redpacket/' . date('Ymd') . '/' . $picurl['savename'];
                }else{
                    $img = '';
                }
                $attribute = array();
                $attribute_title = $_POST['attribute_title'.$i];
                $attribute_value = $_POST['attribute_value'.$i];
                if(!empty($attribute_title)){
                    $attribute = array();
                    foreach ($attribute_title as $key => $val){
                        if($val != ''){
                            $new_attribute = array( $val => $attribute_value[$key] );
                            $attribute = array_merge($attribute, $new_attribute);
                        }
                    }
                }
                $award_data[$i] = array(
                    'item_id' => trim($_POST['item_id'.$i]),
                    'name' => trim($_POST['name'.$i]),
                    'level' => trim($_POST['level'.$i]),
                    'number' => intval(trim($_POST['number'.$i])),
                    'reserve' => trim($_POST['reserve'.$i]),
                    'pic' => $img,
                    'attribute' => serialize($attribute),
                    'status' => RedPacketModel::STATUS_ACTIVE
                );
            }
        }
        return array( 'award_data' => $award_data, 'upload_data' => $upload_data);
    }

    //参与粉丝
    public function fanslist()
    {
        $id = I("get.id","","");
        $fans = M('redpacket_fans');
        $where['pid'] = $id;
        $where['token'] = $this->wxuser['token'];
        $where['status'] = RedPacketModel::STATUS_ACTIVE;

        $count = $fans->where($where)->count();

        $page = new Page($count, 10);
        $show = $page->show();

        $list = $fans->where($where)->limit($page->firstRow.','.$page->listRows)->order('id desc')->select();

        $this->assign("page", $show);
        $this->assign("list", $list);
        $this->display();
    }

    //中奖管理
    public function awardlist()
    {
        $id = I("get.id","","");
        $fansaward = M('redpacket_fansaward');
        $where['pid'] = $id;
        $where['token'] = $this->wxuser['token'];
        $where['status'] = RedPacketModel::STATUS_ACTIVE;
        $where['zhongjiang'] = RedPacketModel::ZHONGJIANG_ACTIVE;

        $count = $fansaward->where($where)->count();

        $page = new Page($count, 10);
        $show = $page->show();

        $list = $fansaward->where($where)->limit($page->firstRow.','.$page->listRows)->order('id desc')->select();
        $awardid = array();
        $award = array();
        $openids = array();
        $fans = array();
        if(!empty($list)){
            foreach ($list as $value){
                $awardid[] = $value['award_id'];
                $openids[] = $value['openid'];
            }
            $items_where['id'] = array('IN', $awardid);
            $items = M('redpacket_item')->where($items_where)->select();
            foreach ($items as $item){
                $award[$item['id']]['award_name'] = $item['name'];
                $award[$item['id']]['award_level'] = RedPacketModel::getLevel($item['level']);
            }
            $fans_where['openid'] = array('IN', $openids);
            $fans_where['pid'] = $id;
            $red_packet_fans = M('redpacket_fans')->where($fans_where)->select();
            foreach ($red_packet_fans as $fan){
                $fans[$fan['openid']]['name'] = $fan['name'];
                $fans[$fan['openid']]['phone'] = $fan['phone'];
            }
        }
        $this->assign("page", $show);
        $this->assign("list", $list);
        $this->assign("award", $award);
        $this->assign("fans", $fans);
        $this->assign("id", $id);
        $this->display();
    }

    public function exportAwards()
    {
        set_time_limit(0);
        $id = I("get.id", "", "");
        if (empty($id)) {
            return $this->redirect("/User/RedPacket/index");
        }
        vendor('phpexcel.PHPExcel');
        $objExcel = new \PHPExcel();
        $objActSheet = $objExcel->getActiveSheet();
        $objActSheet->getColumnDimension('A')->setWidth(20);
        $objActSheet->getColumnDimension('B')->setWidth(30);
        $objActSheet->getColumnDimension('C')->setWidth(20);
        $objActSheet->getColumnDimension('D')->setWidth(20);
        $objActSheet->getColumnDimension('E')->setWidth(20);
        $objActSheet->setCellValue('A1', "姓名");
        $objActSheet->setCellValue('B1', "联系方式");
        $objActSheet->setCellValue('C1', "奖项等级");
        $objActSheet->setCellValue('D1', "奖项名称");
        $objActSheet->setCellValue('E1', "参与时间");
        $condition['pid'] = $id;
        $condition['status'] = RedPacketModel::STATUS_ACTIVE;
        $condition['zhongjiang'] = RedPacketModel::ZHONGJIANG_ACTIVE;
        $condition['token'] = $this->wxuser['token'];
        $line = 2;
        $fansaward = M("redpacket_fansaward");
        $list = $fansaward->where($condition)->order('id desc')->select();
        $awardid = $award = $openids = $fans = array();
        if(!empty($list)){
            foreach ($list as $value){
                $awardid[] = $value['award_id'];
                $openids[] = $value['openid'];
            }
            $items_where['id'] = array('IN', $awardid);
            $items = M('redpacket_item')->where($items_where)->select();
            foreach ($items as $item){
                $award[$item['id']]['award_name'] = $item['name'];
                $award[$item['id']]['award_level'] = RedPacketModel::getLevel($item['level']);
            }
            $fans_where['openid'] = array('IN', $openids);
            $fans_where['pid'] = $id;
            $red_packet_fans = M('redpacket_fans')->where($fans_where)->select();
            foreach ($red_packet_fans as $fan){
                $fans[$fan['openid']]['name'] = $fan['name'];
                $fans[$fan['openid']]['phone'] = $fan['phone'];
            }
            //
            foreach ($list as $value) {
                $objActSheet->setCellValue('A' . $line, $fans[$value['openid']]['name']);
                $objActSheet->setCellValue('B' . $line, $fans[$value['openid']]['phone']);
                $objActSheet->setCellValue('C' . $line, $award[$value['award_id']]['award_name']);
                $objActSheet->setCellValue('D' . $line, $award[$value['award_id']]['award_level']);
                $objActSheet->setCellValue('E' . $line, $value['createdate']);
                $objActSheet->getRowDimension($line)->setRowHeight(20);
                $line++;
            }
        }
        $fileName = '中奖名单' . date('Ymd') . '.xlsx';
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');
        $objWriter = new \PHPExcel_Writer_Excel2007($objExcel);
        $objWriter->save('php://output');
    }
}

?>
